package com.cjh.wechat.core.service.impl;

import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.cjh.wechat.commom.pojo.Account;
import com.cjh.wechat.commom.pojo.Account.LoginType;
import com.cjh.wechat.commom.pojo.GetUid;
import com.cjh.wechat.commom.pojo.Team;
import com.cjh.wechat.commom.pojo.User;
import com.cjh.wechat.commom.type.UserStatus;
import com.cjh.wechat.core.dao.AccountDao;
import com.cjh.wechat.core.dao.GetUidDao;
import com.cjh.wechat.core.dao.TeamDao;
import com.cjh.wechat.core.dao.UserDao;
import com.cjh.wechat.core.service.AccountService;

@Service
public class AccountServiceImpl implements AccountService
{
    @Resource
    private AccountDao          accountDao;
    @Resource
    private UserDao             userDao;
    @Resource
    private GetUidDao           getUidDao;
    @Resource
    private TeamDao             teamDao;
    private final static int    no          = 1;
    private final static String INIT_AVATAR = "../img/user.png";
    
    @Override
    @Transactional
    public synchronized String addAccount(String password, String username) throws Exception
    {
        Account account = new Account();
        GetUid getUid = getUidDao.selectByPrimaryKey(no);
        int uid = getUid.getUid();
        getUid.setUid(uid + 1);
        getUidDao.updateByPrimaryKey(getUid);
        account.setId(uid + "");
        account.setPassword(password);
        accountDao.insertSelective(account);
        User user = new User();
        user.setId(uid + "");
        user.setUsername(username);
        user.setAvatar(INIT_AVATAR);
        user.setStatus(UserStatus.HIDE.value);
        user.setSex(1);
        userDao.insertSelective(user);
        Team team = new Team();
        team.setName("默认分组");
        team.setSequence(0);
        team.setUid(uid + "");
        teamDao.insertSelective(team);
        return uid + "";
    }
    
    @Override
    public LoginType checkLogin(String id, String password, String sessionCode, String code)
    {
        if (sessionCode == null)
        {
            return LoginType.SESSIONEXPIRED;// 太久未操作，验证码的session过期
        }
        else if (!sessionCode.equals(code))
        {
            return LoginType.CODEERROR;
        }
        else
        {
            Account account = accountDao.findById(id);
            if (account == null)
            {
                return LoginType.NOEXIST;
            }
            else
            {
                if (account.getPassword().equals(password))
                {
                    return LoginType.SUCCESS;
                }
                else
                {
                    return LoginType.PASSWORDERROR;
                }
            }
        }
    }
}
